<template>
  <div class="app-container">
    <div class="mb8">
      <el-row :gutter="10" v-if="step === 1">
        <el-col :span="1.5">
          <el-input v-model="rows" :placeholder="rowsPlaceholder" size="mini" v-input.int></el-input>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleMultiAdd"
          >添加多行
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="mb20 pb5">
      <el-table v-loading="loading" :data="list" border v-if="step === 1">
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">{{
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="55" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="楼盘" align="center" prop="estateId" min-width="200">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">楼盘</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('estateId,estateName,associateData')">
                  批量复制
                </el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.estateId" filterable placeholder="请选择"
                       @change="handleEstateChange($event, scope.$index)" size="mini"
            >
              <el-option
                v-for="item in allEstateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
              <!--              <div class="estate-empty">-->
              <!--                <div>找不到楼盘？</div>-->
              <!--                <el-button type="text" size="mini" @click="handleAddEstate">点击添加新楼盘</el-button>-->
              <!--              </div>-->
              <template slot="empty">
                <div class="estate-empty">
                  <div>找不到楼盘？</div>
                  <el-button type="text" size="mini" @click="handleAddEstate">点击添加新楼盘</el-button>
                </div>
              </template>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="楼栋" align="center" prop="buildingName" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">楼栋</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('buildingId,buildingName,associateData')">
                  批量复制
                </el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <!--            <el-input v-model="scope.row.buildingName" placeholder="请输入楼栋" size="mini"></el-input>-->
            <el-select v-model="scope.row.buildingId" filterable placeholder="请选择"
                       @change="handleBuildingChange($event, scope.$index)" size="mini"
            >
              <el-option
                v-for="item in associatedData(scope.$index,'buildingList')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
              <template slot="empty">
                <div class="estate-empty" v-if="scope.row.estateId">
                  <div>找不到楼栋？</div>
                  <el-button type="text" size="mini" @click="handleAddBuilding(scope.$index)">点击添加新楼栋</el-button>
                </div>
                <span v-else></span>
              </template>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="单元" align="center" prop="unitName" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">单元</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('unitId,unitName,associateData')">批量复制
                </el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <!--            <el-input v-model="scope.row.unitName" placeholder="请输入单元" size="mini"></el-input>-->
            <el-select v-model="scope.row.unitId" filterable placeholder="请选择"
                       @change="handleUnitChange($event, scope.$index)" size="mini"
            >
              <el-option
                v-for="item in associatedData(scope.$index,'buildingList,unitList')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
              <template slot="empty">
                <div class="estate-empty" v-if="scope.row.estateId&&scope.row.buildingId">
                  <div>找不到单元？</div>
                  <el-button type="text" size="mini" @click="handleAddUnit(scope.$index)">点击添加新单元</el-button>
                </div>
                <span v-else></span>
              </template>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="所在楼层" align="center" prop="floors" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">所在楼层</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('floors,associateData')">批量复制</el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <!--            <el-input v-model="scope.row.floors" v-input.int placeholder="请输入楼层" size="mini"></el-input>-->
            <el-select v-model="scope.row.floors" placeholder="请选择"
                       @change="handleFloorChange($event, scope.$index)" size="mini"
            >
              <el-option
                v-for="item in associatedData(scope.$index,'buildingList,unitList,floors')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
              <template slot="empty">
                <span></span>
              </template>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="房间号" align="center" prop="roomNumber" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">房间号</div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.roomNumber" placeholder="请输入房间号" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="面积" align="center" prop="houseArea" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">面积</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('houseArea')">批量复制</el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.houseArea" v-input.float="2" placeholder="请输入面积" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="朝向" align="center" prop="houseOrientation" width="120">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">朝向</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('houseOrientation')">批量复制</el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.houseOrientation" filterable placeholder="请选择" size="mini"
            >
              <el-option
                v-for="item in dict.type.house_orientation"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="户型" align="center" prop="roomType" width="380">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">户型</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('roomType,hall,toilet')">批量复制</el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-input
                  v-model="scope.row.roomType"
                  style="width: 110px"
                  placeholder=""
                  v-input.int
                  size="mini"
                >
                  <span slot="append">室</span>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="scope.row.hall"
                  style="width: 110px"
                  placeholder=""
                  v-input.int
                  size="mini"
                >
                  <span slot="append">厅</span>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="scope.row.toilet"
                  style="width: 110px"
                  placeholder=""
                  v-input.int
                  size="mini"
                >
                  <span slot="append">卫</span>
                </el-input>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="可住人数" align="center" prop="checkInNumber" width="150">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">可住人数</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini" @click="handleBatchCopy('checkInNumber')">批量复制</el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.checkInNumber" v-input.int placeholder="请输入可住人数" size="mini"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10 text-center" v-if="step === 1">
        <el-button type="primary" size="mini" @click="handleAdd" style="width: 100%;margin: 4px 0;" plain>添加房源
        </el-button>
      </div>
      <el-table v-loading="loading" :data="list" border v-if="step === 2">
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">{{
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column label="房源" min-width="55" align="center">
          <template slot-scope="scope">
            <div>
              {{ scope.row.estateName }}{{ scope.row.buildingName }}栋{{
                scope.row.unitName
              }}单元{{ scope.row.roomNumber }}房
            </div>
          </template>
        </el-table-column>
        <el-table-column label="附加信息" width="150" align="center">
          <template slot-scope="scope">
            <div>
              <el-button type="text" size="medium" @click="handleEdit(scope.$index,'additionalInfo','附加信息')">
                <i class="el-icon-plus" v-if="scope.row.additionalInfo === null"></i>
                <span v-else>编辑</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合作信息" width="150" align="center">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label redDot">合作信息</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini"
                           @click="handleBatchCopy('cooperationInfo')"
                >批量复制
                </el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <div>
              <el-button type="text" size="medium" @click="handleEdit(scope.$index,'cooperationInfo','合作信息')">
                <i class="el-icon-plus" v-if="scope.row.cooperationInfo === null"></i>
                <span v-else>编辑</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="房屋设施" width="150" align="center">
          <template slot="header">
            <div class="table-header">
              <div class="table-header-label">房屋设施</div>
              <div class="table-header-btn">
                <el-button type="text" size="mini"
                           @click="handleBatchCopy('facility')"
                >批量复制
                </el-button>
              </div>
            </div>
          </template>
          <template slot-scope="scope">
            <div>
              <el-button type="text" size="medium" @click="handleEdit(scope.$index,'facility','房屋设施')">
                <i class="el-icon-plus" v-if="scope.row.facility === null"></i>
                <span v-else>编辑</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="mb10 text-center">
      <el-button type="default" size="medium" @click="handleSaveDraft">保存草稿</el-button>
      <el-button type="default" size="medium" @click="handlePrev" v-if="step !== 1">上一步</el-button>
      <el-button type="primary" size="medium" @click="handleNext" v-if="step === 1">下一步</el-button>
      <el-button type="primary" size="medium" @click="handleSubmit" v-if="step === 2">提交</el-button>
    </div>
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="editDialogVisible"
      width="1300px"
      append-to-body
    >
      <component :is="componentType" :data="editData" ref="editForm" @submit="handleSaveEditForm"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveEditForm(false)">保存</el-button>
      </div>
    </el-dialog>
    <!--  添加楼盘弹窗  -->
    <addEstate :visible.sync="addEstateVisible" title="添加楼盘" @success="getAllEstateList"/>
    <!--  添加楼栋弹窗  -->
    <addBuilding :visible.sync="addBuildingVisible" title="添加楼栋" :is-designated-estate="true" :designated-estate="designatedData" @success="handleRefreshAssociateData"/>
    <!--  添加单元弹窗  -->
    <addUnit :visible.sync="addUnitVisible" title="添加单元" :designatedData="designatedData" @success="handleRefreshAssociateData"/>

  </div>
</template>
<script>
import { estateList, getRelevance, listEstate } from '@/api/house/estate'
import additionalInfo from '@/views/house/room/batchAdd/components/additional-info.vue'
import cooperationInfo from '@/views/house/room/batchAdd/components/cooperation-info.vue'
import facility from '@/views/house/room/batchAdd/components/facility.vue'
import addEstate from '@/views/house/estate/component/add.vue'
import addBuilding from '@/views/house/building/components/add.vue'
import addUnit from '@/views/house/building/components/addUnit.vue'
import { batchAdd } from '@/api/house/room'

export default {
  name: 'batchAdd',
  components: { additionalInfo, cooperationInfo, facility, addEstate,addBuilding,addUnit },
  dicts: [
    'house_orientation'
  ],
  data() {
    return {
      rows: null,
      maxRows: 30,
      step: 1,
      loading: false,
      // 添加小区弹窗
      addEstateVisible: false,
      // 添加楼栋弹窗
      addBuildingVisible: false,
      // 添加单元弹窗
      addUnitVisible: false,
      // 指定小区数据
      designatedData: {},
      // 全小区列表
      allEstateList: [],
      list: [],
      queryParams: {},
      // 编辑房源信息弹窗数据
      editData: {},
      // 编辑房源信息弹窗索引
      editDataIndex: null,
      componentType: 'additionalInfo',
      // 编辑房源信息标题
      editDialogTitle: '',
      // 编辑房源信息弹窗
      editDialogVisible: false,
      rules: {
        estateId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ],
        buildingName: [
          { required: true, message: '请输入楼栋', trigger: 'blur' }
        ],
        unitName: [
          { required: true, message: '请输入单元', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入所在楼层', trigger: 'blur' }
        ],
        roomNumber: [
          { required: true, message: '请输入房间号', trigger: 'blur' }
        ],
        houseArea: [
          { required: true, message: '请输入面积', trigger: 'blur' }
        ],
        houseOrientation: [
          { required: true, message: '请选择朝向', trigger: 'change' }
        ],
        roomType: [
          { required: true, message: '请输入室数', trigger: 'blur' }
        ],
        hall: [
          { required: true, message: '请输入厅数', trigger: 'blur' }
        ],
        toilet: [
          { required: true, message: '请输入卫数', trigger: 'blur' }
        ],
        checkInNumber: [
          { required: true, message: '请输入可住人数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    rowsPlaceholder() {
      return `请输入行数,最多${this.maxRows - this.list.length}行`
    },
    associatedData: {
      get() {
        return (index, keys) => {
          let keyArr = keys.split(',')
          let list = []
          if (keyArr.length === 1 && this.list[index].associateData[keyArr[0]]) {
            list = this.list[index].associateData[keyArr[0]].map(item => {
              return {
                value: item.buildingId,
                label: item.buildingName
              }
            })
          } else if ((keyArr.length === 2 || keyArr.length === 3) && this.list[index].associateData[keyArr[0]]) {
            let building = this.list[index].associateData[keyArr[0]].find(item => item.buildingId === this.list[index].buildingId)
            if (keyArr.length === 2) {
              if (building && building.unitList) {
                list = building.unitList.map(unit => {
                  return {
                    value: unit.unitId,
                    label: unit.unitName,
                    floors: unit.floors
                  }
                })
              }
            }

            if (keyArr.length === 3 && building && building.unitList) {
              let unit = building.unitList.find(item => item.unitId === this.list[index].unitId)
              if (unit) {
                for (let i = 0; i < unit.floors; i++) {
                  list.push({
                    label: i + 1,
                    value: i + 1
                  })
                }

              }
            }
          }
          if (list.length === 0) {
            return []
          }

          return list
        }
      }
    }
  },
  created() {
    this.getAllEstateList()
    this.loadDraft()
  },
  methods: {
    // 加载草稿
    loadDraft() {
      let batchAddHouseList = localStorage.getItem('batchAddHouseList') ? JSON.parse(localStorage.getItem('batchAddHouseList')) : []
      let item = batchAddHouseList.find(item => item.userId === this.$store.state.user.id)
      if (item) {
        this.$confirm('是否加载草稿？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.list = item.houseList
        }).catch(() => {
          //清空草稿
          this.handleCancelDraft()
        })
      }

    },
    //
    /** 获取小区列表 */
    getAllEstateList() {
      estateList().then(response => {
        this.allEstateList = response.data.map(item => {
          return {
            value: item.estateId,
            label: item.estateName,
            ...item
          }
        })
      })
    },
    /** 添加小区弹窗 */
    handleAddEstate() {
      this.addEstateVisible = true
    },
    // 添加新楼栋
    handleAddBuilding(index) {
      console.log('添加新楼栋', index)
      this.designatedData = {
        estateId: this.list[index].estateId,
        estateName: this.list[index].estateName
      }
      this.addBuildingVisible = true
    },
    // 添加新单元
    handleAddUnit(index) {
      console.log('添加新单元', index)
      this.designatedData = {
        estateId: this.list[index].estateId,
        estateName: this.list[index].estateName,
        buildingId: this.list[index].buildingId,
        buildingName: this.list[index].buildingName
      }
      this.addUnitVisible = true
    },
    //刷新关联数据
    handleRefreshAssociateData() {
      getRelevance(this.designatedData.estateId).then(response => {
        let data = response.data
        let associateData = {}
        associateData['estateId'] = response.data.estateId
        associateData['estateName'] = response.data.estateName
        associateData['buildingList'] = data.buildingList.map(building => {
          return {
            buildingId: building.buildingId,
            buildingName: building.buildingName,
            unitList: building.unitList.map(unit => {
              return {
                unitId: unit.unitId,
                unitName: unit.unitName,
                floors: unit.floors
              }
            })
          }
        })
        this.list.filter(item => item.estateId === this.designatedData.estateId).forEach(item => {
          item.associateData = associateData
        })
        this.$forceUpdate()
      })
    },
    // 添加多行
    handleMultiAdd() {
      console.log('添加多行')
      if (!this.rows) {
        this.$message.error('请输入行数')
        return
      }
      if (this.rows > this.maxRows - this.list.length) {
        this.$message.error(`最多只能再添加${this.maxRows - this.list.length}行`)
        return
      }
      this.loading = true
      for (let i = 0; i < this.rows; i++) {
        let item = {
          associateData: {},//关联数据
          estateId: '',//小区id
          estateName: '',//小区名
          buildingId: '',//楼栋id
          buildingName: '',//楼栋
          unitId: '',//单元id
          unitName: '',//单元
          floors: '',//所在楼层
          roomNumber: '',//房间号
          houseArea: '',//面积
          houseOrientation: '',//朝向
          roomType: '',// 室数
          hall: '',// 厅数
          toilet: '',// 卫数
          checkInNumber: '',//可住人数
          // waterMeterNumber: '',//水表号
          // electricMeterNumber: '',//电表号
          // gasMeterNumber: '',//燃气表号
          // rentalLicenseNumber: '',//房屋租赁许可证号
          // houseCheckCode: '',//房源核验码
          additionalInfo: null,//附加信息
          cooperationInfo: null,//合作信息
          facility: null//房屋设施
        }
        this.list.push(item)
      }
      this.$nextTick(() => {
        this.loading = false
      })
    },
    // 处理添加房源
    handleAdd() {
      console.log('添加房源')
      let i = [
        {
          'facilitiesItemList': [
            {
              'facilitiesId': 2, //房屋设施id
              'facilitiesNumber': 1, //设施数量
              'facilitiesPrice': 50, //设施价格
              'facilitiesState': 1, //设施状态：1正常 2已损坏
              'facilitiesName': '房屋设施名' //房屋设施名
            }
          ], //房屋设施集合
          'roomNumber': '', //房间号
          'estateId': '', //楼盘id
          'estateName': '', //楼盘名称
          'buildingId': '', //楼栋id
          'buildingName': '', //楼栋名称
          'houseArea': null, //房屋面积
          'roomType': '', //室
          'hall': '', //厅
          'toilet': '', //卫
          'houseOrientation': '', //朝向
          'waterMeterNumber': '', //水表号
          'electricMeterNumber': '', //电表号
          'gasMeterNumber': '', //燃气表
          'unitId': '', //单元id
          'unitName': '', //单元名称
          'floors': null, //层数
          'checkInNumber': null, //可住人数
          'cooperationType': '1', //合作方式:1.房屋委托;2.代理服务
          'chargeType': '1', //收费方式:1.账单服务费;2.一次性服务费
          'serviceCharge': null, //账单服务费
          'feeAmount': null, //费用金额
          'latestPaymentDate': '', //最晚付款日期
          'rentalLicenseNumber': '', //房屋租赁许可证号
          'houseCheckCode': '', //房源核验码
          'houseManagerId': 3, //房管家id
          'houseManagerName': '房管家名字', //房管家名字
          'houseManagerPhone': '房管家电话', //房管家电话
          'proprietorUserId': 1, //业主id
          'proprietorName': '业主姓名' //业主姓名
        }
      ]
      let item = {
        associateData: {},//关联数据
        estateId: '',//小区id
        estateName: '',//小区名
        buildingId: '',//楼栋id
        buildingName: '',//楼栋
        unitId: '',//单元id
        unitName: '',//单元
        floors: '',//所在楼层
        roomNumber: '',//房间号
        houseArea: '',//面积
        houseOrientation: '',//朝向
        roomType: '',// 室数
        hall: '',// 厅数
        toilet: '',// 卫数
        checkInNumber: '',//可住人数
        // waterMeterNumber: '',//水表号
        // electricMeterNumber: '',//电表号
        // gasMeterNumber: '',//燃气表号
        // rentalLicenseNumber: '',//房屋租赁许可证号
        // houseCheckCode: '',//房源核验码
        additionalInfo: null,//附加信息
        cooperationInfo: null,//合作信息
        facility: null//房屋设施

      }
      // 如果大于30条，提示
      if (this.list.length >= this.maxRows) {
        this.$message.error('已超过最大限制，请删除部分房源后再添加')
        return
      }
      this.list.push(item)
    },
    // 处理删除房源
    handleDelete(index) {
      console.log('删除房源', index)
      this.list.splice(index, 1)
    },
    // 处理小区选择
    handleEstateChange(value, index) {
      console.log('小区选择', value)
      this.list[index].estateId = value
      this.list[index].estateName = this.allEstateList.find(item => item.value === value).label
      this.list[index].buildingId = ''
      this.list[index].buildingName = ''
      this.list[index].unitId = ''
      this.list[index].unitName = ''
      this.list[index].floors = ''
      getRelevance(value).then(response => {
        let data = response.data
        let associateData = {}
        associateData['estateId'] = response.data.estateId
        associateData['estateName'] = response.data.estateName
        associateData['buildingList'] = data.buildingList.map(building => {
          return {
            buildingId: building.buildingId,
            buildingName: building.buildingName,
            unitList: building.unitList.map(unit => {
              return {
                unitId: unit.unitId,
                unitName: unit.unitName,
                floors: unit.floors
              }
            })
          }
        })
        this.list[index].associateData = associateData
      })
    },
    // 处理楼栋选择
    handleBuildingChange(value, index) {
      console.log('楼栋选择', value)
      this.list[index].buildingId = value
      this.list[index].buildingName = this.associatedData(index, 'buildingList').find(item => item.value === value).label
      this.list[index].unitId = ''
      this.list[index].unitName = ''
      this.list[index].floors = ''
    },
    // 处理单元选择
    handleUnitChange(value, index) {
      console.log('单元选择', value, index)
      this.list[index].unitId = value
      this.list[index].unitName = this.associatedData(index, 'buildingList,unitList').find(item => item.value === value).label
      this.list[index].floors = ''
    },
    handleFloorChange(value, index) {
      console.log('楼层选择', value, index)
      this.list[index].floors = value
    },
    // 批量复制
    handleBatchCopy(keys) {
      console.log('批量复制', keys)
      // 获取第一行数据
      let firstItem = this.list[0]
      // 处理需要复制的keys 字符串 转数组
      let keysArr = keys.split(',')
      for (let i = 0; i < keysArr.length; i++) {
        keysArr[i] = keysArr[i].trim()
      }
      // 判断是否有数据
      if (this.list.length <= 1) {
        this.$message.error('请至少再添加一条数据')
        return
      }
      // 判断对应字段是否有值
      for (let i = 0; i < keysArr.length; i++) {
        let key = keysArr[i]
        console.log(key, firstItem[key])
        if (!firstItem[key]) {
          this.$message.error(`请先输入第一行的内容`)
          return
        }
      }
      this.loading = true
      // 遍历列表，复制第一行数据
      for (let i = 1; i < this.list.length; i++) {
        let item = this.list[i]
        for (let j = 0; j < keysArr.length; j++) {
          let key = keysArr[j]
          item[key] = firstItem[key]
          if (key === 'estateId') {
            item['buildingId'] = ''
            item['buildingName'] = ''
            item['unitId'] = ''
            item['unitName'] = ''
            item['floors'] = ''
          }
          if (key === 'buildingId') {
            item['estateId'] = firstItem['estateId']
            item['estateName'] = firstItem['estateName']
            item['unitId'] = ''
            item['unitName'] = ''
            item['floors'] = ''
          }
          if (key === 'unitId') {
            item['estateId'] = firstItem['estateId']
            item['estateName'] = firstItem['estateName']
            item['buildingId'] = firstItem['buildingId']
            item['buildingName'] = firstItem['buildingName']
            item['floors'] = ''
          }
          if (key === 'floors') {
            item['estateId'] = firstItem['estateId']
            item['estateName'] = firstItem['estateName']
            item['buildingId'] = firstItem['buildingId']
            item['buildingName'] = firstItem['buildingName']
            item['unitId'] = firstItem['unitId']
            item['unitName'] = firstItem['unitName']
          }
        }
      }
      this.$nextTick(() => {
        this.loading = false
        this.$message.success('批量复制成功')
      })

    },
    // 保存草稿
    handleSaveDraft() {
      if (this.list.length === 0) {
        this.$message.error('请至少添加一条房源')
        return
      }
      let batchAddHouseList = localStorage.getItem('batchAddHouseList') ? JSON.parse(localStorage.getItem('batchAddHouseList')) : []
      let item = {
        userId: this.$store.state.user.id,
        houseList: this.list
      }
      let index = batchAddHouseList.findIndex(item => item.userId === this.$store.state.user.id)
      if (index !== -1) {
        batchAddHouseList.splice(index, 1, item)
      } else {
        batchAddHouseList.push(item)
      }
      localStorage.setItem('batchAddHouseList', JSON.stringify(batchAddHouseList))
      this.$message.success('保存成功')
    },
    // 取消草稿
    handleCancelDraft() {
      let batchAddHouseList = localStorage.getItem('batchAddHouseList') ? JSON.parse(localStorage.getItem('batchAddHouseList')) : []
      let index = batchAddHouseList.findIndex(item => item.userId === this.$store.state.user.id)
      if (index !== -1) {
        batchAddHouseList.splice(index, 1)
        localStorage.setItem('batchAddHouseList', JSON.stringify(batchAddHouseList))
      }
    },
    // 上一步
    handlePrev() {
      console.log('上一步')
      if (this.step === 1) {
        return
      }
      this.step--

    },
    // 下一步
    handleNext() {
      console.log('下一步')
      if (this.list.length === 0) {
        this.$message.error('请至少添加一条房源')
        return
      }
      // 校验数据
      // 楼盘相同、楼栋相同、单元相同、楼层相同的前提下，房间号相同的房源不能重复
      let roomList = this.list.map(item => `${item.estateName}${item.buildingName}${item.unitName}${item.floors}${item.roomNumber}`)
      for (let i = 0; i < this.list.length; i++) {
        let item = this.list[i]
        if (!item.estateId) {
          this.$message.error(`第${i + 1}行小区不能为空`)
          return
        }
        if (!item.buildingName) {
          this.$message.error(`第${i + 1}行楼栋不能为空`)
          return
        }
        if (!item.unitName) {
          this.$message.error(`第${i + 1}行单元不能为空`)
          return
        }
        if (!item.floors) {
          this.$message.error(`第${i + 1}行所在楼层不能为空`)
          return
        }
        if (!item.roomNumber) {
          this.$message.error(`第${i + 1}行房间号不能为空`)
          return
        }
        if (!item.houseArea) {
          this.$message.error(`第${i + 1}行面积不能为空`)
          return
        }
        if (!item.houseOrientation) {
          this.$message.error(`第${i + 1}行朝向不能为空`)
          return
        }
        if (!item.roomType || !item.hall || !item.toilet) {
          this.$message.error(`第${i + 1}行户型不能为空`)
          return
        }
        if (!item.checkInNumber) {
          this.$message.error(`第${i + 1}行可住人数不能为空`)
          return
        }
        // 校验房间号是否重复
        let room = `${item.estateName}${item.buildingName}${item.unitName}${item.floors}${item.roomNumber}`
        let sameIndexArr = []
        roomList.forEach((item, index) => {
          if (item === room && index !== i) {
            sameIndexArr.push(index + 1)
          }
        })
        console.log('校验房间号是否重复', sameIndexArr, i)
        if (sameIndexArr.length > 0) {
          return this.$message.error(`第${sameIndexArr.join('、')}行房源与第${i + 1}行房源重复`)
        }
      }
      this.step++
    },
    // 处理编辑房源
    handleEdit(index, type, title) {
      console.log('编辑房源', index, type)
      this.editDataIndex = index
      this.componentType = type
      this.editDialogTitle = title
      this.editData = this.list[index][this.componentType] ? JSON.parse(JSON.stringify(this.list[index][this.componentType])) : null
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.init()
      })

    },
    // 保存表单数据
    handleSaveEditForm(data) {
      if (data) {
        console.log('保存表单数据', data)
        this.list[this.editDataIndex][this.componentType] = data
        this.closeEditDialog()
      } else {
        this.$refs.editForm.handleSubmit()
      }
    },
    // 关闭编辑弹窗
    closeEditDialog() {
      this.editDialogVisible = false
      this.$refs.editForm.resetForm()
    },
    // 提交
    handleSubmit() {
      console.log('提交')
      if (this.list.length === 0) {
        this.$message.error('请至少添加一条房源')
        return
      }
      let formData = []
      // 校验数据
      for (let i = 0; i < this.list.length; i++) {
        // 判断合作信息是否为空
        if (this.list[i].cooperationInfo === null) {
          this.$message.error(`第${i + 1}行合作信息不能为空`)
          return
        }

        // // 判断房屋设施是否为空
        // if (this.list[i].facility === null) {
        //   this.$message.error(`第${i + 1}行房屋设施不能为空`)
        //   return
        // }
        // // 判断房屋设施是否为空
        // if (this.list[i].additionalInfo === null) {
        //   this.$message.error(`第${i + 1}行附加信息不能为空`)
        //   return
        // }
        let itemData = {
          facilitiesItemList: this.list[i].facility ? this.list[i].facility.facilitiesItemList : [],
          estateId: this.list[i].estateId,//小区id
          estateName: this.list[i].estateName,//小区名
          buildingId: this.list[i].buildingId,//楼栋id
          buildingName: this.list[i].buildingName,//楼栋
          unitId: this.list[i].unitId,//单元id
          unitName: this.list[i].unitName,//单元
          floors: this.list[i].floors,//所在楼层
          roomNumber: this.list[i].roomNumber,//房间号
          houseArea: this.list[i].houseArea,//面积
          houseOrientation: this.list[i].houseOrientation,//朝向
          roomType: this.list[i].roomType,// 室数
          hall: this.list[i].hall,// 厅数
          toilet: this.list[i].toilet,// 卫数
          checkInNumber: this.list[i].checkInNumber,//可住人数,
          ...this.list[i].cooperationInfo,//合作信息
          ...this.list[i].additionalInfo//附加信息
        }
        // 判断附加信息是否为空
        if (!this.list[i].additionalInfo) {
          itemData = {
            ...itemData,
            waterMeterNumber: '',//水表号
            electricMeterNumber: '',//电表号
            gasMeterNumber: '',//燃气表号
            rentalLicenseNumber: '',//房屋租赁许可证号
            houseCheckCode: ''//房源核验码
          }
        }

        formData.push(itemData)
      }
      console.log('提交表单数据', formData)
      batchAdd(formData).then(response => {
        console.log('提交房源结果', response)
        this.$message.success(response.msg || '提交成功')
        this.list = []
        this.step = 1
        // 清除草稿
        this.handleCancelDraft()
      })
    }
  }

}
</script>
<style scoped lang="scss">
.table-header {
  .table-header-label {
    &.redDot {
      &:before {
        content: "*";
        color: #f5222d;
        margin-right: 4px;
      }
    }
  }
}

.estate-empty {
  display: flex;
  justify-content: center;
  align-items: baseline;
  padding: 10px;
  color: #999;
  font-size: 14px;
}
</style>
